package com.leadbank.baselbf.leadutils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class ImageUtils {


    /**
     * 压缩图片到2M 以内
     * @param context
     * @param imageFile
     */
    public static void compressImageTo2M(Context context, String imageFile) {

        Uri uri = Uri.fromFile(new File(imageFile));
        //参数可调，值越大图片大小越小
        //options.inSampleSize = inSampleSize;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        //参数可调，值越大图片大小越小
        // 从图片文件或 Bitmap 对象获取输入流
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            // 创建 Bitmap 对象
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);


            // 动态压缩图片到 2M 以内
            int maxSize = 2 * 1024 * 1024; // 2M
            int quality = 100;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);

            while (outputStream.toByteArray().length > maxSize) {
                outputStream.reset();
                quality -= 10;
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            }


            // 获取压缩后的字节数组
            byte[] compressedBytes = outputStream.toByteArray();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

    }
}
